package com.gitee.xmhzzz.component.shutdown.graceful.erureka;

import com.gitee.xmhzzz.component.shutdown.graceful.event.ApplicationUpEvent;
import com.netflix.appinfo.InstanceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration;
import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * @ClassName UpEurekaClient
 * @Description
 * @Author wzq
 * @Date 2023/12/15 16:24
 * @Version 1.0
 */
@Component
@ConditionalOnBean(EurekaServiceRegistry.class)
@ConditionalOnProperty(value = "xmhzzz.graceful.shutdown.enable", havingValue = "true")
public class UpEurekaClient {
    private static final Logger log = LoggerFactory.getLogger(UpEurekaClient.class);

    @EventListener
    public void upEventListener(ApplicationUpEvent upApplicationEvent) {
        try {
            long beginTime = System.currentTimeMillis();
            log.info("UpEurekaClient start  beginTime :{}", beginTime);
            ApplicationContext applicationContext = (ApplicationContext) upApplicationEvent.getSource();
            EurekaServiceRegistry eurekaServiceRegistry = applicationContext.getBean(EurekaServiceRegistry.class);
            EurekaRegistration eurekaRegistration = applicationContext.getBean(EurekaRegistration.class);
            if (eurekaRegistration.getEurekaClient() == null) {
                log.warn("eurekaClient实例已在容器销毁");
                return;
            }
            eurekaServiceRegistry.setStatus(eurekaRegistration, InstanceInfo.InstanceStatus.UP.name());
            long consumingTimeTotal = System.currentTimeMillis() - beginTime;
            log.info("UpEurekaClient  done, consuming time total(ms):{} ", consumingTimeTotal);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
